//生活圈首页

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:myflutter/life_circle_bean/life_circle_home_entity.dart';
import 'package:myflutter/net/api_config.dart';
import 'package:myflutter/net/http_util.dart';
import 'package:myflutter/utils/sp_util.dart';
import 'package:myflutter/utils/util.dart';
import 'package:myflutter/utils/widget_util.dart';
import 'package:toast/toast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'lifecirclepicdetail.dart';
import 'lifecirclevideodetail.dart';


class LifeCircleMainRoute extends StatefulWidget{

  const LifeCircleMainRoute({Key? key}) : super(key: key);

  @override
  LifeCircleMainState createState() => LifeCircleMainState();
}


class LifeCircleMainState extends State<LifeCircleMainRoute>{

  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.white, //修改页面的背景
        //修改AppBar的主体样式
        appBarTheme: const AppBarTheme(
            backgroundColor: Colors.green,
            elevation: 0,  //隐藏AppBar底部的阴影分割线
            systemOverlayStyle: SystemUiOverlayStyle.light //设置状态栏的背景
        ),
        visualDensity: VisualDensity.standard
       ),
        title: "生活圈主页",
        home: const Scaffold(
          body: SafeArea(
              child: LifeCircleMainWidget()),
        ),
    );
  }
}

//生活圈首页布局
class LifeCircleMainWidget extends StatefulWidget{
  const LifeCircleMainWidget({Key? key}) : super(key: key);
  @override
  LifeCircleMainWidgetState createState() => LifeCircleMainWidgetState();
}


class LifeCircleMainWidgetState extends State{

  // 记录推荐时候选中(改变字体颜色和大小)
   bool recommendIsSelected =true;
   int curentPageIndex =0;
   PageController? pageController;

   @override
  void initState() {
     super.initState();
     pageController = PageController(initialPage: curentPageIndex);
   }
  @override
  Widget build(BuildContext context) {
    var children = <Widget>[];
    // 生成2 个 Tab 页
    for (int i = 0; i < 2; ++i) {
      children.add(Page( text: '$i'));
    }
     return Column(
       children: [
         LifeCircleMainTitleWidget(recommendIsSelected: recommendIsSelected,onChanged:_changeTitleStyle),
         Expanded(child: PageView(controller: pageController,onPageChanged:onPageChanged,children:children,))
       ],
     );
  }
   void _changeTitleStyle(bool recommendIsSelected){
     setState(() {
      this.recommendIsSelected =!recommendIsSelected;
      if(this.recommendIsSelected){
        curentPageIndex =0;
      }else{
        curentPageIndex =1;
      }
      pageController?.animateToPage(curentPageIndex, duration: const Duration(milliseconds: 300), curve: Curves.linear,	);
     });
   }

   //Page页面改变监听
   void onPageChanged(int pageIndex){
     setState(() {
       if(pageIndex ==0){
         recommendIsSelected =true;
       }else{
         recommendIsSelected =false;
       }
     });
   }
}


//生活圈title 布局
class LifeCircleMainTitleWidget extends StatefulWidget{
  @override
  LifeCircleMainTitleWidgetState createState() => LifeCircleMainTitleWidgetState();

  LifeCircleMainTitleWidget({Key? key, this.recommendIsSelected = true, required this.onChanged}):super(key:key);

  // 用来记录推荐时候选中(改变字体颜色和大小)
  final ValueChanged<bool> onChanged;
  bool recommendIsSelected =true;
}

class LifeCircleMainTitleWidgetState extends State<LifeCircleMainTitleWidget>{

  @override
  Widget build(BuildContext context) {

    return  //title布局
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: (){
              ToastContext().init(context);
              Toast.show("发布页面待开发", duration: Toast.lengthShort, gravity:  Toast.center);
            },
            child:const Padding(padding: EdgeInsets.only(left: 10),
              child: Image(image: AssetImage("assets/images/icon_camera.png"),width: 30,height: 30,),
            )
            ,),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              GestureDetector(
                onTap: (){
                  widget.onChanged(widget.recommendIsSelected);
                },
                child: Padding(padding: const EdgeInsets.only(right: 10), child:Text("推荐",
                  style: TextStyle(
                    fontSize:widget.recommendIsSelected ? 15 :13,
                    color: widget.recommendIsSelected  ? Colors.black : Colors.grey ,
                  )
                  ,),
                ),
              ),
              GestureDetector(onTap: (){
                widget.onChanged(widget.recommendIsSelected);
              },
                child:  Text("关注", style: TextStyle(
                  fontSize: !widget.recommendIsSelected  ? 15 :13,
                  color: !widget.recommendIsSelected  ? Colors.black : Colors.grey ,
                )),),
            ],
          ),
          GestureDetector(
            onTap: (){
              ToastContext().init(context);
              Toast.show("个人中心待开发", duration: Toast.lengthShort, gravity:  Toast.center);

            },
            child:const Padding(padding: EdgeInsets.only(right: 10),
              child: Text("个人中心"),
            )
            ,),
        ],
      );
  }
}

// Tab 页面
class Page extends StatefulWidget {
  const Page({
    Key? key,
    required this.text
  }) : super(key: key);

  final String text;

  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {

  //分页加载请求
  int pageIndex=0;
  //item 数据
  List<LifeCircleHomeData>? data =[];
  final RefreshController _refreshController = RefreshController(initialRefresh: false);

   @override
  void initState() {
    super.initState();
    //请求接口首页
     WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
       _request(pageIndex);
      });
    }

//    推荐列表数据
void _request(int pageindex) async{

  Response response = await HttpUtil.instance.post(ApiConfig.lifecirclemain,showLoading:true,context: context);
  if (response.data['code'] == "SUCCESS") {
    LifeCircleHomeEntity lifeCircleHomeEntity  = LifeCircleHomeEntity().fromJson(response.data['data']);
     if(pageIndex==0){
         data!.clear();
         data = lifeCircleHomeEntity.data;
       _refreshController.refreshCompleted();
     }else if(pageIndex > 0 ){
          var data = lifeCircleHomeEntity.data;
           if(null != data){
             this.data!.addAll(data);
             _refreshController.loadComplete();
           }else{
             _refreshController.loadNoData();
           }
     }
    if (mounted) {
      setState(() {

      });
    }
  } else {

  }


}

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 10,right: 10,top: 15),
      child:
      SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: const WaterDropHeader(),
        footer: CustomFooter(
          builder: (context,mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  const Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  const CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = const Text("加载失败！");
            }
            else if(mode == LoadStatus.canLoading){
              body = const Text("松手,加载更多!");
            }
            else{
              body = const Text("没有更多数据了!");
            }
            return SizedBox(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child:  StaggeredGridView.countBuilder(
            shrinkWrap: true,
            crossAxisCount: 4,
            crossAxisSpacing: 7,
            mainAxisSpacing: 10,
            itemCount: data!.length,
            itemBuilder: (context, index) {
              return LifeCircleMainItemWidget(data![index]);
            },
            staggeredTileBuilder: (index) =>
                StaggeredTile.fit(2)),
      ),

    );
  }

  void _onRefresh() async{

      _request(0);
  }

  void _onLoading() async{
      pageIndex =pageIndex+1;
     _request(pageIndex);

  }
}

//生活圈瀑布流item布局
class LifeCircleMainItemWidget extends StatefulWidget{

   LifeCircleMainItemWidget(this.data,{Key? key}) : super(key: key);

    LifeCircleHomeData?  data;

  @override
  LifeCircleMainItemWidgetState createState() => LifeCircleMainItemWidgetState();

}

class LifeCircleMainItemWidgetState extends State<LifeCircleMainItemWidget>{
   String defauleUrl ="https://img0.baidu.com/it/u=3365573645,2073973856&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500";
  @override
  Widget build(BuildContext context) {
      String? thumbnail = widget.data?.imgVideo[0].thumbnail;
      String? coverPic = widget.data?.imgVideo[0].coverPic;
      print("build----");
    return GestureDetector(
          onTap: (){
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return  widget.data!.type !="img" ?
              LifeCircleDetaipVedioMainRoute(widget.data?.imgVideo[0].completeStandUrl??"",widget.data?.imgVideo[0].thumbnail??""):
              LifeCircleDetaipPicMainRoute(widget.data);
                 return const Text("nihaoya",style: TextStyle(color: Colors.green),);
                 },
               ),
              );
          },
          child: Column(
          crossAxisAlignment:CrossAxisAlignment.start,
          children: [
            Stack(
             alignment: AlignmentDirectional.center,
              children: [
              ClipRRect(borderRadius:BorderRadius.circular(7.0),child:FadeInImage(placeholder:const AssetImage("assets/images/icon_placeholder.gif"),
                  image: NetworkImage(widget.data?.type!="img"?(thumbnail??defauleUrl):(coverPic?? defauleUrl)),
                imageErrorBuilder : (context, error, stackTrace) {
        return Container(
           child: Image.asset("assets/images/icon_error.png",fit: BoxFit.fill,),
           height: 150,
           color: Colors.grey,
        );
        }
           ),
              ),
              Visibility(visible: widget.data?.type != "img",child: Image.asset("assets/images/icon_play.png",width: 40,height: 40,))
                ],),

             Padding(padding: const EdgeInsets.only(top: 5),child: Text(widget.data!.title),),
            Padding(padding: const EdgeInsets.only(top: 5),
              child:Row(
                mainAxisAlignment :MainAxisAlignment.spaceBetween,
                children: [
                  //头像和昵称
                  Row(children: [SizedBox(
                    child: ClipOval(
                      child: WidgetUtil.buildAvatar(widget.data?.users.avatar),
                    ),
                    width: 20,
                    height: 20,
                  ),
                    Padding(padding: const EdgeInsets.only(left: 4),child: Text(utils.getNickNmae(widget.data?.users.nickname),style: const TextStyle(fontSize: 12,color: Colors.black),),)
                  ],),
                  //  浏览数据
                  //浏览量
                  Row(children: const [
                    Image(image: AssetImage("assets/images/icon_look.png"),width: 12,height: 12,),
                    Padding(padding: EdgeInsets.only(left: 2),child: Text("1001",style: TextStyle(fontSize: 11,color: Colors.black),),),
                  ],),
                ],
              ),
            ),
          ],
        ),
     );
  }
}


